<?
class Blink{
        
        /**
        * Logs in users.
        * @params
        * @user: user name as entered
        * @type: usertype, important to access levels
        * @pass: the password (unencrypted)
        * @return: array with user id and name or false
        */
        
        function login($user,$pass){
            //make sure all data are passed.
            if($user && $pass){
                //encrypt the pass
                $pass = md5($pass);
                //get the data
                $res = dbQuery("select userid,user,pass,utypeid from users where user='".$user."' and pass = '".$pass."' and active='1'") or die(dbError());
                //1 row only
                $row = dbFetchArray($res);
                if(is_array($row)){
                    //get what levels he can reach
                    $levels = $this->GetUserLevels($row['utypeid']);
                    //get user home page
                    $homepage = $levels['home'];
                    
                    //construct the array
                    $ret = array("id"=>$row['userid'],"user"=>$row['user'],"utypeid"=>$row['utypeid'],"levels"=>$levels['levels']);
                    //return true
                    return $ret;
                }else{
                    return array("error"=>"Wrong credentials");
                } 
            }else{
                return array("error"=>"All fields are reuired");
            }
        }
        /**
        * gets user total information (points, transactions ...etc)
        * @params
        * @userid: got from session
        * @type: usertype, important to access levels
        * @pass: the password (unencrypted)
        * @return: array with user id and name or false
        */
        function GetUserStatement($uid){
            
        }
        
        /**
        * gets token information from userid
        * @params
        * @userid: 
        * @return: 64 length token
        */
        function GetToken($user){
            $res = dbQuery("select token from users where userid='".$user."'") or die(dbError());
            $row = dbFetchArray($res);
            return $row['token'];
        }
        
        
        function Validate($user, $pass, $dob){
            $res =dbQuery("select userid from users where user ='".$user."'") or die(dbError());
            if($row = dbFetchArray($res))
                return array("error"=>1);
            if(strlen($pass) < $config['passlen'])
                return array("error"=>2);
            if(strlen($user) < $config['userlen'])
                return array("error"=>3);
        
            return true;
        }
        
        /**
        * Gets user allowed levels as per the db
        * @params
        * @type: User type / group
        * @return: levels he's allowed into, array
        */
        function GetUserLevels($type){
            $res = dbQuery("select moduleid from ACL where utypeid='".$type."' and allow='1'") or die(dbError());
                    //get access levels
                    while($row2 = dbFetcharray($res)){
                        $levels[] = $row2['moduleid'];
                    }
            $res = dbQuery("select homepage from utypes where utypeid='".$type."' ") or die(dbError());
            $row=dbFetchArray($res);
            $home = $row['homepage'];
                    return array("levels"=>$levels,"home"=>$home);
        }
        
        
        /**
        * checks permission levels,each page will have the height level that can access it coded right into it, so if that type of user is allowed to access it he will pass
        * @params
        * @levels: array contains the user types allowed into this page
        * @type: usertype, important to access levels
        * @return: allowed or not
        */
        function CheckPermission($type,$levels){
            foreach ($levels as $level){
              if($type == $level)
                return true;
            }
            return false;
        }
        
        /**
        * Gets user tickets
        * @params
        * @uid: user id 
        * @return: a view of tickets to be plugged anywhere.
        */
        function GetUserTickets($uid){
                $view = new view();
                $view->title 						= "My tickets";
                $view->query 						= "select ticketid, title,d.name,s.name from tickets t left outer join departments d on (t.departmentid = d.departmentid) left outer join status s on (t.statusid = s.statusid) where t.userid = '".$uid."'";
                $view->properties['headers'] 		= array('ticket ID'=>"",'title '=>"","department"=>"", "status"=>"","View"=>"<a href='threads.php?ticketid=##ticketid##'>View</a>");
                $view->properties['style']		= "tablesorter";
                $view->properties['cols']		= '5';
                $view->properties['deleteurl']		= 'HandleSubmit.php';
                $view->properties['deleteparam']	= array('index'=>'##ticketid##','indexname'=>'departmentid','submit'=>'DELETE','t'=>$form->table);
                $parse = $view->CreateView();
                return $parse;
            }
        /**
        * Gets active categories
        * @params
        * None 
        * @return: list of active categories
        */
        
        function GetCategories(){
                $res = dbQuery('select catid,catname,discount from categories where active=1');
                while ($row= dbFetchArray($res)){
                    $result[$row['catid']] = $row['catname']."|".$row['discount'];
                    }
                return $result;
                
            }
            
        /**
        * Gets active promotions
        * @params
        * None 
        * @return: list of active promotions, featured promotion with description
        */
        
        function GetPromotions(){
                $res = dbQuery("select promoid,title,description,end,featured,url from promotions where end > '".date("Y-m-d")."'") or die(dbError());
                while($row = dbFetchArray($res)){
                    if($row['featured'] == "1"){
                        $featured = array("promoid"=>$row['promoid'],"title"=>$row['title'],"description"=>$row['description'],"end"=>$row['end']);
                    }
                    $result[$row['promoid']] = $row['title']."|".$row['end'];
                }
                $return = array("featured"=>$featured,"result"=>$result);
                return $return;
            }
        
        
        
        function CreateTicket($uid,$title,$body,$department){
            
        }
        /**
        * Gets all shops (brief) in the category
        * @params
        * category id
        * @return: array with shopid->name, logo comes from uploads/slogo-shopid.jpg 
        */
        function GetCatShops($catid){
            $res = dbQuery("select shopid,name,catname,url from shops left outer join categories on (shops.catid=categories.catid) where shops.catid='".$catid."'") or die(dbError());
            while($row = dbFetchArray($res)){
                $catname = $row['catname'];
                $ret[$row['shopid']] = array("name"=>$row['name'],"url"=>$row['url']);
            }
            return array("ret"=>$ret,"cat"=>$catname);
        }
        /**
        * Gets shop details for shop page
        * @params
        * shopid
        * @return: array with shopid->name, description,slogo logo comes from uploads/slogo-shopid.jpg 
        */
        function GetShopDetails($shopid){
             $res = dbQuery("select shopid,name,description from shops where shopid ='".$shopid."'") or die(dbError());
            while($row = dbFetchArray($res)){
                $ret[$row['shopid']] = array("name"=>$row['name'],"description"=>$row['description'],"logo"=>"slogo-".$row['shopid'].".jpg");
            }
            return $ret;
        }

        /**
	 * Replaces keys placed between ## from the row in the db with actual values according to the query
	 *
	 * @param dbrow $row
	 * @param the string $string
	 * @return link, a string
	 */
	function ReplaceKeys($row,$string){
		reset($row);
		while(list($key,$value) = each($row)){
			$keys[] = "[".$key."]";
			$values[] = $value;	
		}
		$link = str_replace($keys,$values,$string);
	return $link;
	}
        
        /**
	 * Gets promotion details by promotion id
	 *
	 * @param promoid
	 * @return $row of data
	 */
	function GetPromotion($promoid){
            $res = dbQuery("select promoid,title,description,end,url,shopid from promotions where promoid='".$promoid."'") or die(dbError());
            $row= dbFetchArray($res);
            return $row;
        }
        
        /**
	 * Gets promotion details by promotion id
	 *
	 * @param promoid
	 * @return $row of data
	 */
	function GetRelatedByShopid($shopid){
            $res = dbQuery("select catid from shops where shop ='".$shopid."'") or die(dbError());
            $row= dbFetchArray($res);
            $catid = $row['catid'];
            
            //get related shops
            $res = dbQuery("select shopid,name,description,url from shops where catid='".$catid."' limit 0,5");
            while($row2 = dbFtechArray($res)){
                $ids[] = $row2['shopid'];
                $shops[$row2['shopid']] = array("name"=>$row2['name'],"description"=>$row2['description'],"url"=>$row2['url']);
            }
            
            //get related promotions
            $res =dbQuery("select promoid,title,description,end,url from promotions where shopid in ('".join(",",$ids)."')");
            while ($row = dbFetchArray($res)){
                $promotions[$row['promoid']] = array("title"=>$row['title'],"description"=>$row['description'],"end"=>$row['end'],"url"=>$row['url']);
            }
            
            return array("shops"=>$shops, "promotions"=>$promotions);
        }
        
        /**
	 * Gets user/shop by token
	 *
	 * @param token
	 * @return userid
	 */
	function GetByToken($token,$type){
            $res = dbQuery("select ".$type."id from ".$type."s where token='".$token."'") or die(dbError());
            $row = dbFetchArray($res);
            return $row[$type.'id'];
        }
        
        /**
	 * performs transaction
	 *
	 * @param userid
	 * @param shopid
	 * @param transid: transaction id as sent by shop
	 * @param unique: random string to validate sent by shop
	 * @param direction: in or out
	 * @param total: total money paid
	 * @param comission: actual commission paid to bonuslink
	 * @return userid
	 */
	function Transact($user,$shop,$total,$comission,$direction,$trans,$random,$ushare){
            //TODO: Check on transaction id and unique strings, so they would not be repeated.
            $share = $comission * $ushare;
            $res =dbQuery("insert into transactions (shopid,userid,transid,direction,totalprice,comission,uniqueid,ushare) values('".$shop."','".$user."','".$trans."','".$direction."','".$total."','".$comission."','".$random."','".$share."')");
            
            return true;
        }
        
        
        function GetUserTransactions($id,$type,$dir){
            $res = dbQuery("select id,s.name,ushare,totalprice,approved from transactions t left outer join shops s on (s.shopid = t.shopid) where t.".$type."id='".$id."' and direction='".$dir."'") or die(dbError());
            while ($row = dbFetchArray($res)){
                $trans[$row['id']] = array("shop"=>$row['name'],"save"=>$row['ushare'],"total"=>$row['total'],"status"=>$row['approved']);
            }
            return $trans;
        }
        
        
        
}
?>